import { history } from 'umi'
import { message } from 'antd'
import { STORATE_KEY } from '@/constant'
import { login } from '@/services/login'
import { queryCurrent } from '@/services/user'
import { queryNotices } from '@/services/user'

export const INITIAL_STATE = {
  status: undefined, // 登录状态
  collapsed: false, // 菜单收缩标记
  authority: '', // 当前角色权限
  currentUser: {}, // 用户信息
  notices: [], // 公告信息
}

const GlobalModel = {
  namespace: 'global',
  state: INITIAL_STATE,
  effects: {
    // 登录
    *login(
      {
        payload: { data = {}, callback },
      },
      { call, put }
    ) {
      const { data: loginRes = {} } = yield call(login, data)
      if (loginRes && loginRes.code === 0) {
        const res = loginRes.data || {}
        localStorage.setItem(STORATE_KEY.TOKEN, res.token)
        localStorage.setItem(STORATE_KEY.USER_INFO, JSON.stringify(res))
        message.success('登录成功')
        // const { data: currentUser = {} } = yield call(queryCurrent)
        // if (currentUser) {
        //   yield put({
        //     type: 'changeLoginStatus',
        //     payload: {
        //       ...loginRes,
        //       status: loginRes.status,
        //       type: loginRes.type,
        //       authority: currentUser.currentAuthority,
        //       currentUser,
        //     },
        //   })
        //   history.replace('/dashboard')
        // }
        yield put({
          type: 'changeLoginStatus',
          payload: {
            authority: 'admin',
            currentUser: res,
          },
        })
        history.replace('/dashboard')
      } else {
        callback && callback()
      }
    },
    // 退出登录
    *logout(_, { put }) {
      if (window.location.pathname !== '/login') {
        yield put({
          type: 'changeLoginStatus',
          payload: INITIAL_STATE,
        })
        localStorage.clear()
        history.replace({ pathname: '/login' })
      }
    },
    // 获取当前用户信息
    *fetchCurrent(_, { call, put }) {
      const { data: currentUser = {} } = yield call(queryCurrent)
      yield put({
        type: 'saveCurrentUser',
        payload: {
          currentUser,
          authority: currentUser.currentAuthority,
        },
      })
    },
    // 获取公告
    *fetchNotices(_, { call, put, select }) {
      const data = yield call(queryNotices)
      yield put({
        type: 'saveNotices',
        payload: data,
      })
      const unreadCount = yield select(
        state => state.global.notices.filter(item => !item.read).length
      )
      yield put({
        type: 'changeNotifyCount',
        payload: {
          totalCount: data.length,
          unreadCount,
        },
      })
    },
    // 清除公告
    *clearNotices({ payload }, { put, select }) {
      yield put({
        type: 'saveClearedNotices',
        payload,
      })
      const count = yield select(state => state.global.notices.length)
      const unreadCount = yield select(
        state => state.global.notices.filter(item => !item.read).length
      )
      yield put({
        type: 'changeNotifyCount',
        payload: {
          totalCount: count,
          unreadCount,
        },
      })
    },
    // 公告标记已读
    *changeNoticeReadState({ payload }, { put, select }) {
      const notices = yield select(state =>
        state.global.notices.map(item => {
          const notice = { ...item }

          if (notice.id === payload) {
            notice.read = true
          }

          return notice
        })
      )
      yield put({
        type: 'saveNotices',
        payload: notices,
      })
      yield put({
        type: 'changeNotifyCount',
        payload: {
          totalCount: notices.length,
          unreadCount: notices.filter(item => !item.read).length,
        },
      })
    },
  },
  reducers: {
    // 保存用户信息
    saveCurrentUser(state, { payload }) {
      return { ...state, ...payload }
    },
    // 登录、登出
    changeLoginStatus(state, { payload }) {
      return { ...state, ...payload }
    },
    // 菜单收缩
    changeLayoutCollapsed(state, { payload }) {
      return { ...state, ...payload }
    },
    // 保存公告
    saveNotices(state, { payload }) {
      return {
        collapsed: false,
        ...state,
        notices: payload,
      }
    },
    // 保存清除的公告
    saveClearedNotices(
      state = {
        notices: [],
        collapsed: true,
      },
      { payload }
    ) {
      return {
        collapsed: false,
        ...state,
        notices: state.notices.filter(item => item.type !== payload),
      }
    },
    changeNotifyCount(
      state = {
        currentUser: {},
      },
      action
    ) {
      return {
        ...state,
        currentUser: {
          ...state.currentUser,
          notifyCount: action.payload.totalCount,
          unreadCount: action.payload.unreadCount,
        },
      }
    },
  },
  subscriptions: {},
}
export default GlobalModel
